from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client


@deconstructible
class FastDFSStorage(Storage):

    def __init__(self, client_conf=None, base_url=None):

        if client_conf is None:
            client_conf = settings.CLIENT_CONF

        self.client_conf = client_conf

        if base_url is None:
            base_url = settings.BASE_URL

        self.base_url = base_url

    # 打开图片的业务逻辑
    def _open(self, name, mode='rb'):
        """
        Retrieves the specified file from storage.
        """
        pass

    # 保存图片的业务逻辑
    def _save(self, name, content, max_length=None):

        # 生成fastdfs链接对象
        c = Fdfs_client(self.client_conf)

        # 调用upload_by_buffer方法文件上传(buffer读取二进制文件)
        static = c.upload_by_buffer(content.read())

        # 判断是否上传成功
        if static['Status'] != 'Upload successed.':
            # 上传失败
            raise Exception('upload error上传失败')

        # 上传成功
        # 获取路径
        file_id = static['Remote file_id']

        return file_id

    def url(self, name):

        # 拼接完整路径
        return self.base_url + name

    # 判断文件是否重复
    def exists(self, name):

        return False

